package com.fantasy.ui;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.fantasy.EventListener;
import com.fantasy.R;
import com.fantasy.TaskController;
import com.fantasy.User;
import com.fantasy.WimNotificationManager;
import com.fantasy.msg.IPMComEvent;
import com.fantasy.msg.IPMEvent;
import com.fantasy.msg.IPMListener;
import com.fantasy.msg.IPMPack;
import com.fantasy.msg.IPMsg;
import com.fantasy.util.Constant;
import com.fantasy.util.Cp932;
import com.fantasy.util.IMUtil;
import com.fantasy.util.LogOpt;
import com.fantasy.util.SortVector;

public class MainWimActivity extends ListActivity {
	private static final String TAG = "MainWimActivity";
	private static final boolean DEBUG = true;
    public IPMsg mIpMsg;


    private Hashtable mName2Info = new Hashtable();

    private Hashtable mAddr2Info = new Hashtable();

    private boolean mRefreshing = false;

    private boolean mReceived = false;
    
	private boolean mIsBound = false;
	private static final int DIALOG_QUIT = 0;
	private static final int DIALOG_NEW_MESSAGE = 3;

	private static final int MESSAGE_USER_LOGIN = 1;
	private static final int MESSAGE_USER_QUIT = 2;
	private static final int MESSAGE_RESUME = 5;

	private static final int MENU_QUIT = 4;
	private static final String WIM_SERVICE_NAME = "com.fantasy.service.WimService";

	private ArrayList<String> mMemberList = new ArrayList<String>();
	private UIEventListener mListener = new UIEventListener();
	private TaskController mTc;
	private UserAdapter mAdapter;
	private boolean mIm;
	private boolean mWimServiceRunning = false;

	private String mMessageContent = null;
	private String mFromIp = null;
	
	WimNotificationManager mWm;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case MESSAGE_USER_LOGIN:
			case MESSAGE_USER_QUIT:
			    if (LogOpt.D) {
			        Log.v(TAG,"notifydataSetchanged");
			    }
				mAdapter.notifyDataSetChanged();
				break;
			case MESSAGE_RESUME:
				mAdapter.notifyDataSetChanged();
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_wim_activity);

		if (DEBUG) {
			Log.d(TAG, "myself ip address:" + IMUtil.getHostIPAddress());
		}
		mWm = new WimNotificationManager(this);
		mAdapter = new UserAdapter(MainWimActivity.this, mMemberList);
		initView();
		// initData();
		// start();
	}

	private void startTask() {
		mTc = TaskController.getInstance();
		if (DEBUG)
			Log.d(TAG, "register:listener");
		mTc.registerObserver(mListener);
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (DEBUG) {
			Log.d(TAG, "bindWimService:");
		}
		// bindWimService();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent();
		intent.putExtra(MessageBoxActivity.MESSAGE_IP, mMemberList
				.get(position));
		if (DEBUG) {
			Log.d(TAG, "onListItemClick:" + mMemberList.get(position));
		}
		/*
		 * intent.putExtra(ConversionActivity.TARGET_NAME,
		 * mUserList.get(position).userName);
		 */
		intent.setClass(MainWimActivity.this, MessageBoxActivity.class);
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// return super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_QUIT, 0, getString(R.string.quit_applition));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_QUIT:
			showDialog(DIALOG_QUIT);
			return true;
		}
		return false;
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case DIALOG_QUIT:
			return new AlertDialog.Builder(this).setMessage(
					R.string.tip_dialog_quit).setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							Log.d(TAG, "click ok button:" + which);
							if (!isFinishing()) {
								mWm.cancelNotifcation();
								finish();
							}

						}
					}).setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							Log.d(TAG, "click cancel button:" + which);
							return;
						}
					}).create();
		case DIALOG_NEW_MESSAGE:
			return new AlertDialog.Builder(this).setTitle(mFromIp).setMessage(
					mMessageContent).setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

						}
					}).create();
		}

		return super.onCreateDialog(id, args);
	}

	private class UserAdapter extends BaseAdapter {
		LayoutInflater mInflater;
		private Context mContext;
		private ArrayList<String> mUserData;

		public UserAdapter(Context context, ArrayList<String> userlist) {
			mInflater = LayoutInflater.from(context);
			mUserData = userlist;
			mContext = context;
		}

		public int getCount() {
			return mUserData.size();
		}

		@Override
		public void registerDataSetObserver(DataSetObserver observer) {
			super.registerDataSetObserver(observer);

		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mUserData.get(position);
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View v;
			if (convertView == null) {
				v = mInflater.inflate(R.layout.user_item_layout, parent, false);
			} else {
				v = convertView;
			}
			TextView userIpView = (TextView) v.findViewById(R.id.userIp);
			TextView userName = (TextView) v.findViewById(R.id.userName);
			String ip = mUserData.get(position);
			if (userIpView != null) {
				if (DEBUG) {
					Log.d(TAG, "User IP:" + ip);
				}
				userIpView.setText(ip);
			}
			/*if (userName != null) {
				if (DEBUG) {
					Log.d(TAG, "User Name:" + user.userName);
				}
				userName.setText(user.userName);
			}
*/
			return v;
		}

	}

	class IncomingHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (DEBUG) {
				Log.d(TAG, "IncomingHandler:" + msg.what);
			}
			switch (msg.what) {

			}
		}

	}

	private class UIEventListener extends EventListener {

		@Override
		public void addUser(String ip) {
			super.addUser(ip);
			mMemberList.add(ip);
			Message msg = new Message();
			msg.arg1 = MESSAGE_USER_LOGIN;
			mHandler.sendMessage(msg);

		}

		@Override
		public void newMessage(String message) {
			super.newMessage(message);
		}

		@Override
		public void onEvent(ArrayList<User> al) {
			// TODO Auto-generated method stub
			super.onEvent(al);
		}

		@Override
		public void removeUser(String ip) {
			// TODO Auto-generated method stub
			super.removeUser(ip);
			mMemberList.remove(ip);
			Message msg = new Message();
			msg.arg1 = MESSAGE_USER_QUIT;
			mHandler.sendMessage(msg);
		}

	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	private void initView() {
		setListAdapter(mAdapter);
		 mIpMsg = new IPMsg();
	        mIpMsg.addIPMListener(new IPMListener() {

	            @Override
	            public void eventOccured(IPMEvent ev) {
	                processEvent(ev);
	            }

	        });
	        mIpMsg.entry();
	}


    private void processEvent(IPMEvent ev) {
        switch (ev.getID()) {
            case IPMEvent.UPDATELIST_EVENT:
                if (LogOpt.D) {
                    Log.v(TAG, "refresh list");
                }
                mReceived = true;

                if (!mRefreshing) {
                    mRefreshing = true;
                    new RefreshListThread().start();
                }
                break;
            case IPMEvent.RECEIVEMSG_EVENT:
                if (!mIpMsg.lessThanReceiveMax()) {
                    if (LogOpt.D) {
                        Log.v(TAG,"too many receive dialog....");
                    }
                    break;
                }
                mIpMsg.incReceiveCount();
                if (LogOpt.D) {
                    Log.v(TAG,"show receive dialog ");
                }
                break;
            case IPMEvent.READMSG_EVENT:
            case IPMEvent.DELETEMSG_EVENT:
            case IPMEvent.CANTSENDMSG_EVENT:
        }
    }
    

    private class RefreshListThread extends Thread {

        @Override
        public void run() {
            String tmpGroup = Cp932.toJIS(mIpMsg.getPref("allName"));
            if (LogOpt.D) {
                Log.v(TAG,"tmpGroup:" + tmpGroup);
            }
            while (mReceived) {
                mReceived = false;
                try {
                    sleep(500);
                } catch (InterruptedException e) {
                }
                mName2Info = new Hashtable();
                mAddr2Info = new Hashtable();
                Hashtable groupCache = new Hashtable();
                mMemberList.clear();

                //groups.add

                Enumeration members = mIpMsg.getUserlist().elements();
                SortVector tmpVec = new SortVector();
                while (members.hasMoreElements()) {
                    IPMComEvent tmpEvent = (IPMComEvent) members.nextElement();
                    tmpVec.addElement(makeSortKey(tmpEvent), tmpEvent);
                }

                members = tmpVec.elements();
                while (members.hasMoreElements()) {
                    IPMComEvent tmpEvent = (IPMComEvent) members.nextElement();
                    IPMPack tmpPack = tmpEvent.getPack();
                    if (tmpPack.getGroup() != null && groupCache.get(tmpPack.getGroup()) == null) {
                        //groups.addItem
                        groupCache.put(tmpPack.getGroup(), tmpPack.getGroup());
                    }

                    if (LogOpt.D) {
                        Log.v(TAG,"mIpMsg.getPref:" + mIpMsg.getPref("allName"));
                        Log.v(TAG,"tmpPack.getGroup:" + tmpPack.getGroup());
                    }
                    if (!tmpGroup.equals(mIpMsg.getPref("allName"))) {
                        if (tmpPack.getGroup() == null)
                            continue;
                        else if (!tmpPack.getGroup().equals(tmpGroup)) continue;
                    }

                    String tmpStr = Cp932.toCp932(mIpMsg.makeListStr(tmpPack));
                    if (LogOpt.D) {
                        Log.v(TAG, "tmpStr: " + tmpStr);
                    }
                    mMemberList.add(tmpStr);
                    mName2Info.put(tmpStr, tmpEvent);
                    mAddr2Info.put(tmpEvent.getIPMAddress().toString(), tmpEvent);
                    if (mMemberList.size() == 0) {
                        tmpGroup = mIpMsg.getPref("allName");
                        mRefreshing = true;
                    } else {
                        //groups.select
                    }
                }
                if(LogOpt.D) {
                    Log.v(TAG,"mMemberList:" + mMemberList.size());
                }
                mHandler.sendEmptyMessage(MESSAGE_USER_LOGIN);
                mRefreshing = false;
            }
        }
    }

    String makeSortKey(IPMComEvent ipmce) {
        String tmpkey = mIpMsg.getPref("sortKey");
        StringBuffer strbuf = new StringBuffer();
        for (int i = 0; i < tmpkey.length(); i++)
            switch (tmpkey.charAt(i)) {
                case 'u':
                    String tmpuser;
                    if (ipmce.getPack().getExtra() == null)
                        tmpuser = ipmce.getPack().getUser();
                    else
                        tmpuser = ipmce.getPack().getExtra();
                    strbuf.append(tmpuser);
                    break;
                case 'g':
                    if (ipmce.getPack().getGroup() != null)
                        strbuf.append(ipmce.getPack().getGroup());
                    else
                        strbuf.append("  ");
                    break;
                case 'h':
                    strbuf.append(ipmce.getPack().getHost());
                    break;
            }
        return new String(strbuf);

    }
	protected void onStop() {
		super.onStop();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		/*
		 * switch (keyCode) { case KeyEvent.KEYCODE_BACK: Log.d(TAG,
		 * "@@@@@@@@@@@@@kyeCOde_back");
		 * 
		 * return false; }
		 */
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// mTc.stopAllThread();
	}

	public boolean isServiceRunning(Context mContext, String className) {

		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);
		Log.d(TAG, "isServiceRunning:serviceList.size:" + serviceList.size());
		if (!(serviceList.size() > 0)) {
			return false;
		}
		Log.d(TAG, "@@@@@@@@className:" + className);
		for (int i = 0; i < serviceList.size(); i++) {
			Log.d(TAG, "@@@@@@@@@@@@:::"
					+ serviceList.get(i).service.getClassName());
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;

	}

}
